<template>
  <div class="app-container">
    <div class="custom_card">
      <el-card shadow="navar" id="menuFlag">
        <el-row :gutter="15">
          <el-col :span="12" style="height: 84vh; overflow-y: auto">
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
              <MmvTitle title="基本信息"></MmvTitle>
              <el-row :gutter="15">
                <el-col :span="24">
                  <el-form-item label="活动类型" prop="activityType">
                    <dict-tag :options="dict.type.activityType" :value="formData.activityType" />
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="formData.activityType == 3">
                  <el-form-item label="模板类型">
                    <el-radio-group v-model="formData.templateType" size="medium" @change="changeTemplateType">
                      <el-radio :label="1">优惠券图文活动</el-radio>
                      <el-radio :label="2">车型图文活动</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="活动门店" prop="applicableUnit">
                    <el-select v-model="formData.applicableUnit" @change="applicableUnitNoChange" multiple
                      placeholder="请选择活动门店" clearable :style="{ width: '100%' }">
                      <el-option v-for="item in applicableUnitOptions" :key="item.storeId" :label="item.storeName"
                        :value="item.storeId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="业务类型" prop="bizType">
                    <el-radio-group v-model="formData.bizType" size="medium" @change="changeBizType">
                      <el-radio v-for="dict in tenantBusiness" :key="dict.busId" :label="parseInt(dict.busId)">{{
                        dict.busName }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="活动模板">
                    <el-select v-model="couponTemplateType" placeholder="请选择活动模板" clearable :style="{ width: '100%' }"
                      @change="changeTemplateId">
                      <el-option v-if="formData.activityType == 1" v-for="dict in dict.type.coupon_template"
                        :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
                      <el-option v-if="formData.activityType == 2" v-for="dict in dict.type.model_template"
                        :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
                      <el-option v-if="
                        formData.activityType == 3 &&
                        formData.templateType == 1
                      " v-for="dict in dict.type.holiday_coupon_template" :label="dict.label"
                        :value="parseInt(dict.value)" :key="dict.value"></el-option>
                      <el-option v-if="
                        formData.activityType == 3 &&
                        formData.templateType == 2
                      " v-for="dict in dict.type.holiday_model_template" :label="dict.label"
                        :value="parseInt(dict.value)" :key="dict.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="15" v-if="meetTheConditions">
                <MmvTitle title="活动信息"></MmvTitle>
                <el-col :span="24">
                  <el-form-item label="活动名称" prop="activityName">
                    <el-input v-model="formData.activityName" placeholder="请输入活动名称" :maxlength="10" show-word-limit
                      clearable :style="{ width: '100%' }">
                      <el-button slot="append" @click="changeTitle">换一条（{{ currTitleIndex }}/{{
                        activityNameList.length
                      }}）
                      </el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="活动内容" prop="activityContent">
                    <el-input v-model="formData.activityContent" placeholder="请输入活动内容" type="textarea"
                      :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="80" show-word-limit clearable
                      :style="{ width: '80.5%' }" style="border-radius: 4px 0px 0px 4px">
                    </el-input>
                    <el-button @click="changeContent" style="
                        background-color: #f5f7fa;
                        color: #909399;
                        border-radius: 1px;
                      ">换一条（{{ currContentIndex }}/{{
                        activityContentList.length
                      }}）
                    </el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="活动时间" prop="startTime">
                    <el-date-picker clearable size="large" v-model="activityTime" value-format="yyyy.MM.dd"
                      format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期"
                      end-placeholder="结束日期" @change="checkTime">
                    </el-date-picker>
                  </el-form-item>
                </el-col>

                <!----------------------优惠券列表--------------------------->

                <el-col :span="24" v-if="
                  formData.activityType == 1 ||
                  (formData.activityType == 3 && formData.templateType == 1)
                ">
                  <el-form-item label="请选择优惠券" prop="">
                    <el-button type="primary" icon="el-icon-search" size="small" @click="checkCoupon = true">
                      选择优惠券
                    </el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="
                  formData.activityType == 1 ||
                  (formData.activityType == 3 && formData.templateType == 1)
                ">
                  <el-form-item label="" prop="couponManages">
                    <el-table style="margin-top: 10px" :data="formData.couponManages" border>
                      <el-table-column label="优惠券名称" align="center" min-width="120" show-overflow-tooltip
                        prop="couponName" />
                      <el-table-column label="优惠券类别" align="center" min-width="100" show-overflow-tooltip
                        prop="couponCategory">
                        <template slot-scope="scope">
                          <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponCategory" />
                        </template>
                      </el-table-column>
                      <el-table-column label="库存数量" align="center" min-width="100" show-overflow-tooltip
                        prop="remainingNumber"></el-table-column>
                      <el-table-column label="活动数量" align="center" min-width="100" show-overflow-tooltip prop="number">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.number" placeholder="请输入活动数量" type="number"
                            :max="scope.row.remainingNumber" min="0"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="120px" fixed="left" align="center">
                        <template slot-scope="scope">
                          <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>

                <!----------------------车型列表--------------------------->

                <el-col :span="24" v-if="
                  formData.activityType == 2 ||
                  (formData.activityType == 3 && formData.templateType == 2)
                ">
                  <el-form-item label="请选择车型" prop="">
                    <el-button type="primary" icon="el-icon-search" size="small" @click="showCheckModel = true">
                      选择车型
                    </el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="
                  formData.activityType == 2 ||
                  (formData.activityType == 3 && formData.templateType == 2)
                ">
                  <el-form-item label="" prop="carModelList">
                    <el-table style="margin-top: 10px" :data="formData.carModelList">
                      <el-table-column label="车型" align="center" prop="modelInfo" />
                      <el-table-column label="车型下车辆数" align="center" prop="carModelNum" />
                      <el-table-column label="备发车辆数" align="center" prop="standbyNum"></el-table-column>
                      <el-table-column label="活动车辆数" align="center" prop="number">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.number" placeholder="请输入活动数量" type="number"
                            :max="scope.row.number" min="0"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" min-width="180px" align="center">
                        <template slot-scope="scope">
                          <el-button size="mini" type="danger"
                            @click="handleDeletecarModel(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-table style="margin-top: 10px" :data="formData.carModelList">
                      <el-table-column label="车型" align="center" prop="modelInfo" />
                      <el-table-column label="原价格" align="center" prop="averagePrice">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.averagePrice" placeholder="请输入原价格" type="number"
                            min="0"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="特价金额" align="center" prop="presentPrice">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.presentPrice" placeholder="请输入特价金额" type="number"
                            min="0"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="车型照片" align="center" prop="number">
                        <template slot-scope="scope">
                          <imageUpload v-model="scope.row.url" ref="imageUpload1"
                            v-bind:isShowTip="upload.isShowChildTip" v-bind:limit="upload.limit" />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="15" v-if="meetTheConditions">
                <MmvTitle title="其他信息"></MmvTitle>
                <!-- <el-col :span="24">
                  <el-form-item label="展示位置" prop="isHomeRecommend">
                    <el-radio-group
                      v-model="formData.isHomeRecommend"
                      size="medium"
                    >
                      <el-radio
                        v-for="(item, index) in isHomeRecommendOptions"
                        :key="index"
                        :label="item.value"
                        :disabled="item.disabled"
                        >{{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col> -->
                <el-col :span="24">
                  <el-form-item label="发布类型" prop="issueType">
                    <el-radio-group v-model="formData.issueType" size="medium">
                      <el-radio v-for="(item, index) in issueTypeOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="是否精准推送" prop="isAccurateDelivery">
                    <el-radio-group v-model="formData.isAccurateDelivery" size="medium">
                      <el-radio v-for="(item, index) in isAccurateDeliveryOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <div v-if="formData.isAccurateDelivery == 1">
                  <el-col :span="24">
                    <el-form-item label="推送群体" prop="pushGroup">
                      <el-select v-model="formData.pushGroup" placeholder="请输入推送群体" clearable :style="{ width: '100%' }"
                        :disabled="pushGroupNotEdit">
                        <template v-for="dict in dict.type.label_classify">
                          <el-option :label="dict.label" :value="dict.value" :key="dict.value"
                            v-if="dict.value < 6 || dict.value == 8"></el-option>
                        </template>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="推送方式" prop="pushWay">
                      <el-radio-group v-model="formData.pushWay" size="medium">
                        <el-radio v-for="(item, index) in pushWayOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="推送预览">
                      <div style="border: 1px #c0c4cc solid; padding: 15px">
                        <div>精准推送预览:</div>
                        <div>{{ pushContent }}</div>
                      </div>
                    </el-form-item>
                  </el-col>
                </div>

                <el-col :span="24">
                  <el-form-item size="large">
                    <el-button type="primary" @click="submitForm">提交</el-button>
                    <el-button @click="goBack">取 消</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>

          <el-col :span="12" style="height: 84vh">
            <div v-if="meetTheConditions">
              <preview :seckilData="formData" :goodsList="formData.activityType == 1 ||
                (formData.activityType == 3 && formData.templateType == 1)
                ? formData.couponManages
                : formData.carModelList
                " :templateCode="currTemplateCode" :activityUnit="activityUnit" ref="template"></preview>
              <div style="text-align: center; padding-top: 10px">
                <el-button @click="changeOne">更换素材（{{ currTemplateIndex + 1 }}/{{
                  templateList.length
                }}）</el-button>
              </div>
            </div>
          </el-col>
        </el-row>

        <!--  选择优惠券弹框  -->
        <el-dialog title="" :visible.sync="checkCoupon" width="500px" append-to-body :before-close="closeCheckCoupon">
          <MmvTitle title="优惠券">
            <el-button slot="btn" style="position: absolute; right: 0; top: 0"
              @click="showAddCoupon = true">立即创建</el-button>
          </MmvTitle>
          <el-form ref="form" :model="checkCouponForm" label-width="120px">
            <el-form-item label="选择优惠券">
              <el-select v-model="checkCouponForm.couponId" placeholder="请选择优惠券" clearable :style="{ width: '100%' }"
                filterable remote @change="couponChange">
                <el-option v-for="(item, index) in couponList" :key="index" :label="item.couponName"
                  :value="item.couponId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优惠券库存">
              {{
                checkCouponForm.coupon
                  ? checkCouponForm.coupon.remainingNumber || 0
                  : 0
              }}
            </el-form-item>
            <div style="margin-left: 40px; color: #b3b3b3">
              温馨提示:最多选择10张,已选择{{
                formData.couponManages.length
              }}张,还可再选{{ 10 - formData.couponManages.length }}张
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="subCheckCoupon">确 定</el-button>
            <el-button @click="closeCheckCoupon">取 消</el-button>
          </div>
        </el-dialog>

        <!--  选择车型弹框  -->
        <el-dialog title="" :visible.sync="showCheckModel" width="500px" append-to-body
          :before-close="closeCheckCarModel">
          <MmvTitle title="车型"></MmvTitle>
          <el-form ref="form" :model="checkModelForm" label-width="120px">
            <el-form-item label="选择车型">
              <el-select v-model="checkModelForm.modelId" placeholder="请选择车型" clearable filterable remote
                :style="{ width: '100%' }" @change="carModelChange">
                <el-option v-for="(item, index) in modelList" :key="index" :label="item.modelInfo"
                  :value="item.modelId"></el-option>
              </el-select>
            </el-form-item>
            <div style="margin-left: 40px; color: #b3b3b3">
              温馨提示:最多选择5款,已选择{{
                formData.carModelList.length
              }}款,还可再选{{ 5 - formData.carModelList.length }}款
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="subCheckCarModel">确 定</el-button>
            <el-button @click="closeCheckCarModel">取 消</el-button>
          </div>
        </el-dialog>

        <!--  添加优惠券弹框  -->
        <el-dialog title="添加优惠券" :visible.sync="showAddCoupon" width="50%" append-to-body>
          <CouponManageAdd @close="closeAddCoupon"></CouponManageAdd>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getActivityManage,
  addActivityManage,
  updateActivityManage,
  applicableUnitList,
  carModelListByBiz,
  uploadImg,
  listCouponManage,
} from '@/api/marketingManagement/activityManage'

import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import CouponManageAdd from '../../couponManage/add.vue'
import Preview from './preview.vue'
import { listTemplate } from '@/api/system/template'
import html2canvas from 'html2canvas'
import { getJpeg, dom2img } from '@/utils/html-jpeg'
import { tenantBusiness } from '@/api/car/business'
import { getStoreList } from "@/api/car/model";
export default {
  name: "activityManageAdd",
  components: {
    MmvTitle,
    CouponManageAdd,
    Preview,
  },
  dicts: [
    'sys_business',
    'activity_goodsType',
    'coupon_type',
    'activityType',
    'label_classify',
    'coupon_template',
    'model_template',
    'holiday_coupon_template',
    'holiday_model_template',
  ],
  data() {
    return {
      //活动模板
      couponTemplateType: null,
      pushGroupNotEdit: false,
      templateList: [],
      currTemplateIndex: 0,
      currTitleIndex: 0,
      currContentIndex: 0,
      //优惠券相关
      showAddCoupon: false,
      checkCoupon: false,
      couponManageList: [],
      checkCouponForm: {
        couponId: null,
        coupon: null,
      },
      //车型相关
      showCheckModel: false,
      carModelList: [],
      checkModelForm: {
        modelId: null,
        coupon: null,
      },
      tenantBusiness: [],
      upload: {
        title: '',
        fileSize: 5,
        limit: 1,
        isShowChildTip: false,
        isShowParentTip: true,
      },

      //门店相关
      applicableUnitOptions: [], //门店数据

      activityTime: [],
      formData: {
        templateType: 1,
        activityType: 1,
        templateId: undefined,
        activityName: undefined,
        activityContent: undefined,
        startTime: null,
        endTime: null,
        bizType: undefined,
        isHomeRecommend: 1,
        smallProgramCode: 1,
        issueType: 3,
        isAccurateDelivery: 1,
        pushGroup: undefined,
        pushWay: 1,
        marketingTarget: 0,
        pushContent: undefined,
        couponManages: [],
        carModelList: [],
        applicableUnit: [],
        activityTemplate: {},
      },
      rules: {
        activityType: [
          {
            required: true,
            message: '活动类型不能为空',
            trigger: 'change',
          },
        ],
        templateId: [
          {
            required: true,
            message: '请选择活动模板',
            trigger: 'change',
          },
        ],
        activityName: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur',
          },
        ],
        activityContent: [
          {
            required: true,
            message: '请输入活动内容',
            trigger: 'blur',
          },
        ],
        startTime: [
          {
            required: true,
            message: '请选择活动开始时间',
            trigger: 'change',
          },
        ],
        endTime: [
          {
            required: true,
            message: '请选择活动结束时间',
            trigger: 'change',
          },
        ],
        applicableUnit: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个活动支持门店',
            trigger: 'blur',
          },
        ],
        couponManages: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一张优惠券',
            trigger: 'blur',
          },
        ],
        carModelList: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一款车型',
            trigger: 'blur',
          },
        ],
        bizType: [
          {
            required: true,
            message: '业务类型不能为空',
            trigger: 'change',
          },
        ],
        // isHomeRecommend: [
        //   {
        //     required: true,
        //     message: '首页推荐活动不能为空',
        //     trigger: 'change',
        //   },
        // ],
        smallProgramCode: [
          {
            required: true,
            message: '小程序二维码不能为空',
            trigger: 'change',
          },
        ],
        issueType: [
          {
            required: true,
            message: '请至少选择一个发布类型',
            trigger: 'change',
          },
        ],
        isAccurateDelivery: [
          {
            required: true,
            message: '是否精准推送不能为空',
            trigger: 'change',
          },
        ],
        pushGroup: [
          {
            required: true,
            message: '请选择推送群体',
            trigger: 'blur',
          },
        ],
        pushWay: [
          {
            required: true,
            message: '推送方式不能为空',
            trigger: 'change',
          },
        ],
      },

      // isHomeRecommendOptions: [
      //   {
      //     label: '首页轮播',
      //     value: 1,
      //   },
      //   {
      //     label: '活动列表',
      //     value: 2,
      //   },
      // ],
      smallProgramCodeOptions: [
        {
          label: '底部带小程序码',
          value: 1,
        },
        {
          label: '不带小程序码',
          value: 2,
        },
      ],
      issueTypeOptions: [
        {
          label: '全部发布',
          value: 3,
        },
        {
          label: '线上小程序发布',
          value: 1,
        },
        {
          label: '线下门店发布',
          value: 2,
        },
      ],
      isAccurateDeliveryOptions: [
        {
          label: '是',
          value: 1,
        },
        {
          label: '否',
          value: 2,
        },
      ],
      pushWayOptions: [
        {
          label: '全部',
          value: 1,
        },
        {
          label: '短信推送',
          value: 2,
        },
      ],
    }
  },
  computed: {
    currTemplateCode() {
      if (this.templateList.length > 0) {
        return this.templateList[this.currTemplateIndex].code
      } else {
        return ''
      }
    },
    activityNameList() {
      if (!this.templateList || this.templateList.length == 0) {
        return []
      }
      return this.templateList[this.currTemplateIndex].headlineList
    },
    activityContentList() {
      if (!this.templateList || this.templateList.length == 0) {
        return []
      }
      return this.templateList[this.currTemplateIndex].contentList
    },
    meetTheConditions() {
      switch (Number(this.formData.activityType)) {
        case 1:
          if (this.formData.templateId && this.formData.bizType) {
            return true
          } else {
            return false
          }
        case 2:
          if (
            this.formData.templateId &&
            this.formData.bizType &&
            this.formData.applicableUnit?.length > 0
          ) {
            return true
          } else {
            return false
          }
        case 3:
          if (
            this.formData.templateId &&
            this.formData.bizType &&
            this.formData.applicableUnit?.length > 0
          ) {
            return true
          } else {
            return false
          }
      }
      return false
    },
    couponList() {
      return this.couponManageList.filter((item) => {
        let flag = true
        this.formData.couponManages.map((checked) => {
          if (checked.couponId == item.couponId) {
            flag = false
          }
        })
        return flag
      })
    },
    modelList() {
      return this.carModelList.filter((item) => {
        let flag = true
        this.formData.carModelList.map((checked) => {
          if (checked.modelId == item.modelId) {
            flag = false
          }
        })
        return flag
      })
    },
    pushContent() {
      if (this.formData.pushContent) {
        return this.formData.pushContent
      }
      if (this.formData.isAccurateDelivery == 1) {
        let nameArr = this.activityUnit.map((item) => {
          return item.applicableUnit
        })
        let storeName = nameArr.join('、')

        let online = '线上、线下'
        if (this.formData.issueType == 1) {
          online = '线上'
        } else if (this.formData.issueType == 2) {
          online = '线下'
        }

        return (
          '（客户名称）,您好！' +
          (storeName ? storeName : '（门店名称）') +
          '在' +
          (this.formData.startTime || '（活动时间）') +
          '邀您参加“' +
          online +
          (this.formData.activityName || '（活动名称）') +
          '”活动，详情请联系门店或进入门店小程序了解。'
        )
      } else {
        return null
      }
    },
    activityUnit() {
      let arr = []
      this.formData.applicableUnit.map((item) => {
        this.applicableUnitOptions.map((e) => {
          if (e.applicableUnitNo === item) {
            arr.push(e)
          }
        })
      })
      return arr
    },
  },

  created() {
    this.tenantBusinessList()
    this.reset()
    //获取门店
    this.getApplicableUnitList()
    const activityId = this.$route.query.id
    const activityType = this.$route.query.type
    const marketingTarget = this.$route.query.target
    this.formData.activityType = activityType
    this.formData.marketingTarget = marketingTarget
    if (marketingTarget > 0 && marketingTarget < 9) {
      this.formData.pushGroup = marketingTarget
    }
    if (marketingTarget == 18) {
      this.formData.pushGroup = '8'
    }
    if (marketingTarget > 0 && marketingTarget < 9) {
      this.pushGroupNotEdit = true
    } else {
      this.pushGroupNotEdit = false
    }
    if (activityId) {
      getActivityManage(activityId).then((response) => {
        this.formData = response.data
        this.activityTime = [this.formData.startTime, this.formData.endTime]
        this.couponTemplateType = response.data.activityTemplate.templateName
        this.changeTemplateId(this.couponTemplateType, true)
        this.formData.carModelList = response.data.carModelList
        if (
          this.formData.activityType == 1 ||
          (this.formData.activityType == 3 && this.formData.templateType == 1)
        ) {
          if (this.formData.bizType && this.couponTemplateType) {
            this.getCouponList()
          }
        } else {
          if (this.formData.bizType && this.formData.applicableUnit) {
            this.getcarModelList()
          }
        }
        if (
          this.formData.marketingTarget > 0 &&
          this.formData.marketingTarget < 8
        ) {
          this.pushGroupNotEdit = true
        } else {
          this.pushGroupNotEdit = false
        }
        this.$forceUpdate()
      })
    } else {
      if (marketingTarget > 8) {
        let couponTemplateType = marketingTarget
        this.changeTemplateId(couponTemplateType, false)
      }
    }
  },
  methods: {
    tenantBusinessList() {
      tenantBusiness().then((response) => {
        this.tenantBusiness = response.data
      })
    },
    changeTemplateType() {
      if (this.couponTemplateType) {
        this.changeTemplateId(this.couponTemplateType, false)
        this.changGoodsList()
        this.$forceUpdate()
      }
    },
    applicableUnitNoChange(val) {
      this.changGoodsList()
      this.$forceUpdate()
    },
    changeBizType() {
      this.changGoodsList()
      this.$forceUpdate()
    },
    changeTemplateId(type, flag) {
      let templateType = null
      if (this.formData.activityType == 3) {
        templateType = this.formData.templateType
      }
      listTemplate({
        templateClassification: this.formData.activityType,
        templateName: type,
        templateType: templateType,
      }).then((response) => {
        this.couponTemplateType = parseInt(type)
        this.templateList = response.rows
        let index = 0
        let templateId = null
        if (this.templateList[0]) {
          templateId = this.templateList[0].templateId
          index = this.templateList.findIndex((item) => {
            return item.code == this.formData.activityTemplate.code
          })
        }
        this.currTemplateIndex = index >= 0 ? index : 0
        this.formData.templateId = templateId

        this.currTitleIndex = 0
        this.currContentIndex = 0
        if (!flag) {
          this.changeTitle()
          this.changeContent()
          this.changGoodsList()
        }
        this.$forceUpdate()
      })
    },
    changeOne() {
      if (this.templateList.length <= 1) {
        return
      }
      this.currTemplateIndex++
      if (this.currTemplateIndex >= this.templateList.length) {
        this.currTemplateIndex = 0
      }
      this.formData.templateId =
        this.templateList[this.currTemplateIndex].templateId

      this.currTitleIndex = 0
      this.currContentIndex = 0
      this.changeTitle()
      this.changeContent()
    },
    changeTitle() {
      if (this.activityNameList.length == 0) {
        this.formData.activityName = ''
        return
      }

      if (this.currTitleIndex >= this.activityNameList.length) {
        this.currTitleIndex = 0
      }
      this.formData.activityName =
        this.activityNameList[this.currTitleIndex].value
      this.currTitleIndex++
    },
    changeContent() {
      if (this.activityContentList.length == 0) {
        this.formData.activityContent = ''
        return
      }

      if (this.currContentIndex >= this.activityContentList.length) {
        this.currContentIndex = 0
      }
      this.formData.activityContent =
        this.activityContentList[this.currContentIndex].value
      this.currContentIndex++
    },

    changGoodsList() {
      if (
        this.formData.activityType == 1 ||
        (this.formData.activityType == 3 && this.formData.templateType == 1)
      ) {
        this.couponManageList = []
        this.formData.couponManages = []
        if (this.formData.bizType && this.couponTemplateType) {
          this.getCouponList()
        }
      } else {
        this.carModelList = []
        this.formData.carModelList = []
        if (this.formData.bizType && this.formData.applicableUnit) {
          this.getcarModelList()
        }
      }
    },

    //****************选择优惠券相关 start *******************//
    couponChange() {
      if (this.checkCouponForm.couponId) {
        this.couponManageList.map((item) => {
          if (this.checkCouponForm.couponId == item.couponId) {
            this.checkCouponForm.coupon = item
          }
        })
      } else {
        this.checkCouponForm.coupon = null
      }
    },
    handleDelete(index) {
      this.formData.couponManages.splice(index, 1)
    },
    /** 查询优惠券列表 */
    getCouponList() {
      let queryParams = {
        bizClassification: this.formData.bizType,
      }
      listCouponManage(queryParams).then((response) => {
        this.couponManageList = response.data
      })
    },
    subCheckCoupon() {
      if (this.formData.couponManages.length == 10) {
        this.$modal.msgError('最多选择10张优惠券')
        return
      }
      if (this.checkCouponForm.coupon) {
        this.formData.couponManages.push(this.checkCouponForm.coupon)
        this.closeCheckCoupon()
      } else {
        this.$modal.msgError('请选择优惠券')
      }
    },
    closeCheckCoupon() {
      this.checkCouponForm.couponId = null
      this.checkCouponForm.coupon = null
      this.checkCoupon = false
    },
    closeAddCoupon(refresh) {
      this.showAddCoupon = false
      if (refresh) {
        this.getCouponList()
      }
    },
    //****************选择优惠券相关 end *******************//

    //****************选择车型相关 start *******************//
    carModelChange() {
      if (this.checkModelForm.modelId) {
        this.carModelList.map((item) => {
          if (this.checkModelForm.modelId == item.modelId) {
            this.checkModelForm.carModel = item
          }
        })
      } else {
        this.checkModelForm.carModel = null
      }
    },
    handleDeletecarModel(index) {
      this.formData.carModelList.splice(index, 1)
    },
    getcarModelList() {
      carModelListByBiz({
        applicableUnit: this.formData.applicableUnit,
        bizType: this.formData.bizType,
      }).then((response) => {
        this.carModelList = response.rows
      })
    },
    subCheckCarModel() {
      if (this.formData.carModelList.length >= 5) {
        this.$modal.msgError('最多选择5款车型')
        return
      }
      if (this.checkModelForm.carModel) {
        this.formData.carModelList.push(this.checkModelForm.carModel)
        this.closeCheckCarModel()
      } else {
        this.$modal.msgError('请选择车型')
      }
    },
    closeCheckCarModel() {
      this.checkModelForm.modelId = null
      this.checkModelForm.carModel = null
      this.showCheckModel = false
    },
    //****************选择车型相关 end *******************//

    getApplicableUnitList() {
      applicableUnitList().then((res) => {
        this.applicableUnitOptions = res.data
      })
    },
    async generatePictures() {
      try {
        const coverPictures = await dom2img(
          this.$refs.template.$refs.cover.$refs.coverPictures
        )
        let coverForm = new FormData()
        coverForm.append('file', coverPictures)

        const uploadResult = await uploadImg(coverForm)
        this.formData.coverPictures = uploadResult.fileName

        // const listPictures = await getJpeg(
        //   this.$refs.template.$refs.cover.$refs.listPictures
        // )
        // let listForm = new FormData()
        // listForm.append('file', listPictures)
        // const list = await uploadImg(listForm)
        // this.formData.listPictures = list.fileName
      } catch (err) {
        throw err
      }
    },
    checkTime() {
      if (this.activityTime) {
        this.formData.startTime = this.activityTime[0]
        this.formData.endTime = this.activityTime[1]
      } else {
        this.formData.startTime = null
        this.formData.endTime = null
      }
    },
    download2() {
      const coverPictures = this.$refs.template.$refs.cover.$refs.coverPictures // 截图区域
      html2canvas(coverPictures, {
        backgroundColor: '#e8f4ff',
        useCORS: true, // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
      }).then((canvas) => {
        const dataURL = canvas.toDataURL('image/png')
        const creatDom = document.createElement('a')
        document.body.appendChild(creatDom)
        creatDom.href = dataURL
        creatDom.download = '图片'
        creatDom.click()
      })

      const listPictures = this.$refs.template.$refs.cover.$refs.listPictures // 截图区域
      html2canvas(listPictures, {
        backgroundColor: '#e8f4ff',
        useCORS: true, // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
      }).then((canvas) => {
        const dataURL = canvas.toDataURL('image/png')
        const creatDom = document.createElement('a')
        document.body.appendChild(creatDom)
        creatDom.href = dataURL
        creatDom.download = '图片'
        creatDom.click()
      })
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          for (let item in this.formData.couponManages) {
            if (item.remainingNumber < item.number) {
              this.$modal.msgError('优惠券活动数量不能大于优惠券库存!')
              return
            }
          }
          const loading = this.$loading({
            lock: true,
            text: '活动生成中,请稍等...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          try {
            this.generatePictures().then((r) => {
              this.formData.pushContent = this.pushContent
              if (
                !this.formData.marketingTarget &&
                this.formData.activityType == 3
              ) {
                this.formData.marketingTarget = this.couponTemplateType
              }
              if (this.formData.activityType != 3) {
                this.formData.templateType = this.formData.activityType
              }

              if (this.formData.activityId != null) {
                updateActivityManage(this.formData)
                  .then((response) => {
                    loading.close()
                    this.$modal.msgSuccess('修改成功')
                    this.goBack()
                  })
                  .catch((err) => {
                    loading.close()
                    this.$modal.msgSuccess('修改失败')
                  })
              } else {
                addActivityManage(this.formData)
                  .then((response) => {
                    loading.close()
                    this.$modal.msgSuccess('新增成功')
                    this.goBack()
                  })
                  .catch((err) => {
                    loading.close()
                    this.$modal.msgSuccess('修改失败')
                  })
              }
            })
          } catch (e) {
            loading.close()
            this.$modal.msgError('活动生成失败')
          }
        }
      })
    },
    goBack() {
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )

      this.$IVue.$emit('refreshList')
    },
    reset() {
      this.formData = {
        templateType: 1,
        activityType: 1,
        templateId: undefined,
        activityName: undefined,
        activityContent: undefined,
        startTime: null,
        endTime: null,
        bizType: undefined,
        isHomeRecommend: 1,
        smallProgramCode: 1,
        issueType: 3,
        isAccurateDelivery: 1,
        pushGroup: undefined,
        pushWay: 1,
        pushContent: undefined,
        couponManages: [],
        carModelList: [],
        applicableUnit: [],
        marketingTarget: 0,
        activityTemplate: {},
      }
      this.resetForm('elForm')
    },
  },
}
</script>
